package com.sise.netty.基于jboss的序列化方案;

import com.sise.netty.Gzip流应用.GzipUtil;
import com.sise.netty.基于jboss的序列化方案.dto.RequestDto;
import com.sise.netty.基于jboss的序列化方案.serialHandler.MarshallingCodeHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.IOException;
import java.util.Date;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

/**
 * @author idea
 * @data 2019/4/14
 */
public class Client {

    private EventLoopGroup group = null;

    private Bootstrap bootstrap = null;

    private Client() {
        init();
    }

    /**
     * 初始化资源，并且对于bootstrap进行配置绑定
     */
    private void init() {
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class);
    }


    public ChannelFuture doRequest(String host, int port, ChannelHandler... channelHandlers) throws InterruptedException {
        this.bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(MarshallingCodeHandler.buildMarshallingEncoder());
                ch.pipeline().addLast(MarshallingCodeHandler.buildMarshallingDecoder());
                ch.pipeline().addLast(channelHandlers);
            }
        });
        ChannelFuture channelFuture = this.bootstrap.connect(host, port).sync();
        return channelFuture;
    }

    /**
     * 关闭资源
     */
    public void release() {
        this.group.shutdownGracefully();
    }

    public static void main(String[] args) throws InterruptedException, IOException {
        Client client = null;
        ChannelFuture future = null;

        client = new Client();
        future = client.doRequest("localhost", 9090, new ClientHandle());
        Scanner scanner = null;
        while (true) {
            scanner = new Scanner(System.in);
            System.out.println("enter message send to server (enter 'exit' for close client)");
            String line = scanner.nextLine();
            if ("exit".equals(line)) {
                future.channel().writeAndFlush(Unpooled.copiedBuffer(line.getBytes("UTF-8")))
                        .addListener(ChannelFutureListener.CLOSE);
                break;
            }
            //压缩数据处理
            byte[] msg = GzipUtil.zip(line.getBytes());
            RequestDto requestDto = new RequestDto(new Random().nextInt(1000), msg, new Date());

            future.channel().writeAndFlush(requestDto);
            TimeUnit.SECONDS.sleep(1);
        }
        scanner.close();
        client.release();
    }

}
